<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="isShowDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeesList">
          <el-table-column label="序号" sortable="" width="50px" type="index" align="center" :index="indexFN" />
          <el-table-column label="姓名" sortable="" prop="username" align="center" />
          <el-table-column label="工号" sortable="" prop="workNumber" align="center" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" align="center" :formatter="formatterEmployee" />
          <el-table-column label="部门" sortable="" prop="departmentName" align="center" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" align="center">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState" align="center">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280" align="center">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+(row.id))">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="delFN(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageConfig.size"
            :total="total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 引入弹框组件 -->
      <AddEmployee
        :is-show-dialog="isShowDialog"
      ></AddEmployee>
    </div>
  </div>
</template>

<script>
// 引入组件
import PageTools from '@/components/PageTools/index.vue'
import { getAllEmployees, delEmployee } from '@/api/employees'
import Employees from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployee from '@/views/employees/components/add-employee.vue'
export default {
  // 注册组件
  components: { PageTools, AddEmployee },
  data() {
    return {
      // 保存后台返回的所有员工数据
      employeesList: [],
      // 页码
      pageConfig: {
        page: 1,
        size: 5
      },
      // 页码的总数
      total: 0,
      // 字典
      dict: {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职时间': 'timeOfEntry'
      },
      isShowDialog: false
    }
  },

  created() {
    this.getAllEmployees()
  },

  methods: {
    // 删除员工
    async delFN(id) {
      try {
        await this.$confirm('确定要删除吗？')
        await delEmployee(id)
        this.$message.success('删除成功')
        // 如果本来还剩一条数据，删除成功获取新数据 并将页码-1
        if (this.employeesList.length === 1 && this.pageConfig.page > 1) {
          this.pageConfig.page--
        }
        this.getAllEmployees()
      } catch (error) {
        console.log('删除结果报错', error)
      }
    },

    // 导出数据
    async exportExcel() {
      // 1、导出 >> 获取全部数据
      const { rows } = await getAllEmployees({ page: 1, size: this.total })
      console.log('导出的全部数据', rows)
      // 2、数据处理 转换
      const data = rows.map(userObj => {
        return this.objToArr(userObj)
      })
      const header = Object.keys(this.dict)
      // 3、生成 excel
      export_json_to_excel({
        header,
        data
      })
    },

    // 对象转为数组
    objToArr(userObj) {
      const userArr = []

      // 遍历每一个元素
      for (const key in this.dict) {
        const enKey = this.dict[key]
        const value = userObj[enKey]

        if (enKey === 'formOfEmployment') {
          const obj = Employees.hireType.find(item => Number(item.id) === Number(value))
          userArr.push(obj ? obj.value : '未知')
        } else if (enKey === 'timeOfEntry') {
          userArr.push(formatDate(value))
        } else {
          userArr.push(value)
        }
      }
      return userArr
    },

    // 封装所有员工数据
    async getAllEmployees() {
      const { rows, total } = await getAllEmployees(this.pageConfig)
      // 本地服务器没有 enableState 数据，所以再赋值之前自己写入一个
      this.employeesList = rows.map(user => {
        // 给入随机数
        const state = Math.round(Math.random())
        return {
          ...user,
          // 有就用自己的 没有的话就用定义好的state
          enableState: user.enableState || Number(state)
        }
      })
      this.total = total
    },

    // 页码更新 数据也更新
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.getAllEmployees()
    },

    // 让index序号依次叠加
    indexFN(index) {
      return (this.pageConfig.page - 1) * this.pageConfig.size + index + 1
    },

    formatterEmployee(row, col, cellValue, index) {
      // row 行 col 列
      // cellValue 表格列里面的数据
      // index 当前的索引
      const obj = Employees.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    }
  }
}
</script>

<style scoped>

</style>
